import axios from "axios";

import {ElNotification} from 'element-plus'
import {API_HOST,API_BASE_URL} from "@/config/index.js";
import { ElLoading } from 'element-plus'
// 创建Axios实例
const service = axios.create({
    baseURL:API_HOST+API_BASE_URL, // API基础地址
    timeout: 5000, // 请求超时时间
});

/**
 * 加载条
 * @type {{show(*): void, close(): void}}
 */
const loading = (() => {
    let loadingInstance = null;
    return {
        show(text) {
            loadingInstance = ElLoading.service({
                lock: true,
                text,
                background: "rgba(0, 0, 0, 0.6)",
            });
        },
        close() {
            loadingInstance.close();
        },
    };
})();





// 请求拦截器
service.interceptors.request.use(

    config => {
        loading.show("加载中");
        // 在发送请求之前做些什么，例如添加token
        config.headers['Authorization'] = `Bearer ${localStorage.getItem('token')}`;
        return config;
    },
    error => {
        // 对请求错误做点什么
        console.log(error);
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    response => {
        loading.close();
        const result = response.data
        console.log('请求接口的结果:',result)
        if (result.status!==200) {
            ElNotification({
                title: 'Warning',
                message: result.message||'请求结果不合理',
                type: 'warning',
            })
        }
        return result.data; //取出最终数据
    },
    error => {
        loading.close();
        ElNotification({
            title: 'Error',
            message: error.message||'接口请求出现错误',
            type: 'error',
        })
        return Promise.reject(error.response.data);
    }
);


export default service;
